﻿using Microsoft.WindowsAzure.Storage.Table;
using POC.Azure.Model;
using POC.Azure.Storage;
using POC.Loggers.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace POC.Loggers.Listeners
{
    public class QueueStorageListener : AzureStorageTraceListener
    {
        Diagnostics _logger;
        string queueName;
      
        public QueueStorageListener(): base("async=true")
        {
        }
        public QueueStorageListener(string initializerData)
            : base(initializerData)
        {
          
        }
 
        protected override void InitializeService()
        {
            base.Initialize();
         
                try
                {
                   
                    queueName = this.settings.GetRollingName("queue") ?? this.settings.queueName;

                    MessageFormat format = MessageFormat.Xml;
                    Enum.TryParse<MessageFormat>(this.settings.messageFormat, out format);
                    var repository = new QueueStorageRespository<LogEntry>(this.storageAccount, queueName, format);
                    repository.InitializeRepository();
                    _logger = new Diagnostics(repository);
                }
                catch (Exception colsx)
                {
                    Console.WriteLine(colsx);
                }
            
        }
        protected override void PutEntry(LogEntry entry)
        { 
            if (null == _logger)
                this.InitializeService();
            _logger.PutEntry(entry, async);           
        }
        public override void Flush()
        {
            _logger.Flush(async);
            base.Flush();
        }
    }
}
